from flask import render_template, Blueprint, request

from apps.service.UserService import UserService

from apps.pojo.Entity import UserSchema, User
from apps.util.LayData import LayData

user_bp = Blueprint('user', __name__, url_prefix='/user')

user_schema = UserSchema(many=True)


@user_bp.route('/tolist')
def tolist():
    return render_template('user/list.html')


@user_bp.route('/list',methods=['GET','POST'])
def list():
    page = request.args.get('page', 1, type=int)
    limit = request.args.get('limit', 10, type=int)
    username = request.args.get('username', '', type=str)
    offset = (page - 1) * limit
    userList = UserService.list(username, offset, limit)
    users = user_schema.dump(userList)
    count = UserService.count()
    data = LayData.data(0, '查询成功', count, users)
    return data


@user_bp.route('/toadd')
def toadd():
    return render_template('user/add.html')


@user_bp.route('/addSave',methods=['POST'])
def addSave():
    username = request.form.get('username')
    password = request.form.get('password')
    user = User()
    user.username = username
    user.password = password
    result = UserService.add(user)
    if result:
        return LayData.data2(0, '添加成功')
    else:
        return LayData.data2(500, '添加失败')


@user_bp.route('/toupdate/<int:id>')
def toupdate(id):
    user = UserService.getUserById(id)
    return render_template('user/update.html', user=user)


@user_bp.route('/toinfo/<int:id>')
def toinfo(id):
    user = UserService.getUserById(id)
    return render_template('user/info.html', user=user)

@user_bp.route('/updateSave',methods=['POST'])
def updateSave():
    id = request.form.get('id')
    username = request.form.get('username')
    password = request.form.get('password')
    result = UserService.update(id, username, password)
    if result:
        return LayData.data2(0, '修改成功')
    else:
        return LayData.data2(500, '修改失败')


@user_bp.route('/delete',methods=['POST'])
def delete():
    id = request.form.get('id')
    result = UserService.delete(id)
    if result:
        return LayData.data2(0, '删除成功')
    else:
        return LayData.data2(500, '删除失败')
